Note
Go to the end to download the full example code.
Example of using the QUBO solver on a pool of small random instances.
# pylint: disable=invalid-name
# Maths
import numpy as np
from qtealeaves.optimization import QUBOConvergenceParameter, QUBOSolver
# qtealeaves
from qtealeaves.tensors import TensorBackend
def main(qubo_size=8, n_instances=10, input_folder=None, output_folder=None):
"""Example of a QUBO solver routine on random instances"""
# Creating a small pool of small random (integer) QUBO problems
np.random.seed(11)
qubo_problems = [
np.random.randint(-50, 50, (qubo_size, qubo_size)) for _ in range(n_instances)
]
qubo_problems = [qubo + qubo.T for qubo in qubo_problems]
# Solving the QUBOs and benchmarking with brute-force
print("\n\n")
separator = "-" * 60
for jj, qprob in enumerate(qubo_problems):
my_solver = QUBOSolver(qprob)
print(separator)
print(f"Solving QUBO problem instance n° {jj + 1} . . . ")
## Brute-force for benchmarking
my_solver.solve("brute-force")
bf_config = my_solver.solution[0]
bf_cost = my_solver.cost[0]
print(f" Brute-force solution in {my_solver.time_to_solution} s")
print(f"\t Cost --> {bf_cost}")
print(f"\t Solution --> {bf_config}")
## Tensor-network based solver
## Step 1: define I/O folders
in_folder = input_folder or "./Tensor_Network_Simulation_Input/"
out_folder = output_folder or "./Tensor_Network_Simulation_Output/"
## Tensor-network based solver
## Step 2: define user's parameters for solving the QUBO
my_conv_params = QUBOConvergenceParameter(
max_bond_dimension=8,
max_iter=10,
enable_spacelink_expansion=True,
transverse_field_ratio=1e9,
tn_input_folder_path=in_folder,
tn_output_folder_path=out_folder,
tn_io_extra_tag=f"{jj + 1}",
data_type="C",
device="cpu",
)
## Tensor-network based solver
## Step 3: define the TN backend to be used
## it must match parameters in QUBOConvergenceParameter
my_tn_backend = TensorBackend(device="cpu", dtype=np.complex64)
## Tensor-network based solver
## Step 4: call the TN-based solver
my_solver.solve(
tn_convergence_parameters=my_conv_params, tensor_backend=my_tn_backend
)
## Tensor-network based solver
## Step 5: process results
print(f" Tensor-network solution in {my_solver.time_to_solution} s")
print(f"\t Cost --> {my_solver.cost[0]}")
print(f"\t Solution --> {my_solver.solution[0]}")
print(f"Solving QUBO problem instance n° {jj + 1} . . . done")
print(separator, "\n\n")
# Output
print(f"\nExample `{__file__}` ran successfully; no asserts implemented.")
if __name__ == "__main__":
main()